<template>
    <!-- 在线添加订单 -->
    <el-dialog v-model="addOrderUseOnlineTableVisible" :show-close="false" draggable fullscreen @open="loadingOnlineTable" destroy-on-close>
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">在线添加订单 -- <em style="color: red"> * 为必填项</em> -- ESC关闭</h4>
                <div class="flex gap-2">
                    <!-- 订单号 -->
                    <el-input v-model="addOrderUseOnlineTable.orderNo" placeholder="请输入订单号" clearable @change=""></el-input>
                    <!-- 含税标识 -->
                    <el-switch v-model="addOrderUseOnlineTable.orderTax" inline-prompt active-text="含税价" inactive-text="不含税"></el-switch>
                    <!-- 送货日期 -->
                    <el-date-picker
                        style="width: 400px"
                        v-model="addOrderUseOnlineTable.orderDeliveryDate"
                        type="date"
                        placeholder="请选择送货日期"
                    />
                    <!-- 检查表单数据 -->
                    <el-button type="primary" :icon="TaskComplete" @click="processDataEvent">确认</el-button>
                    <!-- 关闭 -->
                    <el-button type="danger" @click="close">
                        <el-icon class="el-icon--left">
                            <CircleCloseFilled />
                        </el-icon>
                        关闭
                    </el-button>
                </div>
            </div>
        </template>
        <div class="online-table-container" id="onlineTable"></div>
    </el-dialog>
    <!-- 确认导入订单交付 -->
    <el-dialog v-model="importConfirmVisible" :show-close="false" draggable width="80%" destroy-on-close>
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">确认导入订单 -- ESC关闭</h4>
                <div>
                    <el-button type="danger" @click="close">
                        <el-icon class="el-icon--left">
                            <CircleCloseFilled />
                        </el-icon>
                        关闭
                    </el-button>
                </div>
            </div>
        </template>
        <el-descriptions title="订单交付确认" :column="8" border>
            <template #title>
                <el-text type="primary">
                    {{ addOrderUseOnlineTable.orderTax ? '含税' : '不含税' }}总计：{{ addOrderUseOnlineTable.orderAmount }}
                </el-text>
            </template>
            <template #extra>
                <el-button type="primary" @click="confirmImport">确认</el-button>
            </template>
            <div v-for="(item, index) in orderData" :key="index">
                <el-descriptions-item label="检查">
                    <el-text :type="checkOrderDelivery(item).type">{{ checkOrderDelivery(item).message }}</el-text>
                </el-descriptions-item>
                <el-descriptions-item label="订单号"> {{ addOrderUseOnlineTable.orderNo }} </el-descriptions-item>
                <el-descriptions-item label="物料号"> {{ item.materialNumber }} </el-descriptions-item>
                <el-descriptions-item label="产品名称"> {{ item.productName }} </el-descriptions-item>
                <el-descriptions-item label="送货数量"> {{ item.orderNumber }} </el-descriptions-item>
                <el-descriptions-item label="单位"> {{ item.unit }} </el-descriptions-item>
                <el-descriptions-item v-if="!addOrderUseOnlineTable.orderTax" label="不含税单价"> {{ item.excludTaxPrice }} </el-descriptions-item>
                <el-descriptions-item v-if="addOrderUseOnlineTable.orderTax" label="含税单价"> {{ item.includeTaxPrice }} </el-descriptions-item>
                <el-descriptions-item label="小计"> {{ item.subtotal }} </el-descriptions-item>
            </div>
        </el-descriptions>
    </el-dialog>
</template>

<script setup lang="ts">
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { TaskComplete } from '@vicons/carbon';
import '@/components/OnlineTable/assets/js/x-sheet';
import '@/components/OnlineTable/assets/css/x-sheet.css';
import { useUserStore } from '@/store/modules/user';
import { getAllProductList } from '@/api/product';
import { createOrder } from '@/api/order';

onMounted(() => {
    // 初始化
    addOrderUseOnlineTable.customerId = props.customerInfo.customerId;
    addOrderUseOnlineTable.customerName = props.customerInfo.customerName;

    // 获取所有产品列表
    getAllProductList().then((res) => {
        if (res.data.length === 0) {
            ElMessage.error('没有产品信息，请先添加产品信息');
            addOrderUseOnlineTableVisible.value = false;
            return;
        }

        for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index];
            element.products.forEach((product) => {
                productList.push(product);
            });
        }
    });
});

/* ******************************父组件需要传递的属性/方法****************************** */
// model 声明
// 订单弹窗
const addOrderUseOnlineTableVisible = defineModel({ type: Boolean, default: false, required: true });

// props 声明
type customerInfo = {
    customerId: string;
    customerName: string;
    customerAbbreviation: string;
};
const props = defineProps<{
    customerInfo: customerInfo;
}>();

/* ******************************通用属性/方法****************************** */
// 实例
const instance = getCurrentInstance();
// 产品列表
const productList = reactive<AjaxResponse['productList']>([]);
// 匹配产品列表
const matchProductInfo = (productName: string) => {
    return productList.find((item) => item.productName === productName);
};
// 添加订单表单
const addOrderUseOnlineTable = reactive<AjaxRequest['addOrderUseSystemForm']>({
    customerId: '',
    customerName: '',
    orderDate: new Date(),
    orderNo: '',
    orderDeliveryDate: new Date(),
    orderRemark: '',
    orderTax: true,
    orderAmount: 0,
    orderDetail: [],
    creatorId: useUserStore().id,
    creator: useUserStore().username,
});

/* ******************************xSheet属性/方法****************************** */
// xSheet
let xSheet: any = {};
// dialog 打开的时候加载xSheet
const loadingOnlineTable = () => {
    // 初始化
    const settings = {
        workConfig: {
            // 工作簿配置
            created: '', // 创建时间
            modified: '', // 修改时间
            creator: '', // 作者信息
            lastModifiedBy: '', // 最后修改作者
            name: '导入模板', // 工作簿名称---导出的名称
            top: {
                // 顶部配置
                option: {
                    // 顶部选项栏配置
                    show: false, // 是否显示选项栏
                },
                menu: {
                    // 顶部菜单栏配置
                    show: false, // 是否显示菜单栏
                },
            },
            body: {
                // 主体配置
                sheetConfig: {
                    // 工作表菜单配置
                    showMenu: true, // 是否显示右击菜单
                },
                banner: true, // 移除水印
                sheets: [
                    // 工作表主体配置
                    {
                        name: '导入模板', // 工作表名称
                        tableConfig: {
                            // 表格配置
                            data: [
                                // 初始化表数据
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '编号', color: 'rgb(51, 204, 255)' }] },
                                    },
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '物料号', color: 'rgb(51, 204, 255)' }] },
                                    },
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '产品名称*', color: 'rgb(51, 204, 255)' }] },
                                    },
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '订单数量*', color: 'rgb(51, 204, 255)' }] },
                                    },
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '单位（"只"）', color: 'rgb(51, 204, 255)' }] },
                                    },
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '单价*', color: 'rgb(51, 204, 255)' }] },
                                    },
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '备注', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '1', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '2', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '3', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '4', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '5', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '6', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '7', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '8', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '9', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '10', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '11', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '12', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '13', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '14', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '15', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '16', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '17', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '18', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                                [
                                    {
                                        contentType: 2,
                                        fontAttr: { align: 'center', textWrap: 2, direction: 'vertical' },
                                        richText: { rich: [{ text: '19', color: 'rgb(51, 204, 255)' }] },
                                    },
                                ],
                            ],
                            index: {
                                // 标题行列配置
                                displayTopIndex: true, // 是否显示标题行
                                displayLeftIndex: true, // 是否显示标题列
                                height: 30, // 标题行高度
                                width: 50, // 标题列宽度
                                gridColor: 'rgb(193,193,193)', // 标题行列边框颜色
                                size: 12, // 标题行列字体大小
                                color: 'rgb(0,0,0)', // 标题行列字体颜色
                            },
                            table: {
                                // 表格整体配置
                                showGrid: true, // 是否显示网格线
                                background: 'rgb(255,255,255)', // 表格区域背景颜色
                                borderColor: 'rgb(0,0,0)', // 默认边框颜色
                                gridColor: 'rgb(225,225,225)', // 网格线颜色
                            },
                            rows: {
                                // 行配置
                                len: 51, // 自定义最大行数
                                height: 35, // 默认行高
                                data: [], // 行配置数据
                            },
                            cols: {
                                // 列配置
                                len: 7, // 自定义最大列数
                                width: 110, // 默认列宽
                                data: [
                                    // 行配置数据
                                    { col: 0, width: 100 },
                                    { col: 1, width: 250 },
                                    { col: 2, width: 250 },
                                    { col: 3, width: 120 },
                                    { col: 4, width: 200 },
                                    { col: 5, width: 250 },
                                    { col: 6, width: 250 },
                                ],
                            },
                            xFixedView: {
                                // 冻结范围
                                fxLeft: -1, // 冻结列索引，-1为不冻结
                                fxTop: -1, // 冻结行索引，-1为不冻结
                            },
                            xFixedBar: {
                                // 冻结分割线样式
                                height: 16, // 冻结行分割线高度
                                width: 26, // 冻结列分割线宽度
                                background: 'rgb(234,234,234)', // 冻结分割线背景色
                                buttonColor: 'rgb(193,193,193)', // 冻结分割线按钮背景色
                            },
                            protection: {
                                protections: [], // 保护配置
                            },
                            sheetProtection: false, // 是否保护--影响缩放
                        },
                    },
                ],
                tabConfig: {
                    // 工作表选项卡配置
                    showMenu: true, // 是否显示选项卡右击菜单
                },
            },
            bottom: {
                // 底部状态栏配置
                show: true, // 是否显示状态栏
            },
        },
    };

    xSheet = new window.XSheet('#onlineTable', settings);

    const tips = document.querySelector('.x-sheet-version-tips') as HTMLElement;
    tips.style.display = 'none';
};

// 需要导入的订单数据
type orderData = {
    check: boolean;
    price: number;
    productId: string;
    materialNumber: string;
    productName: string;
    productSize: string;
    orderNumber: number;
    unit: string;
    excludTaxPrice: number;
    includeTaxPrice: number;
    subtotal: number;
    remark: string;
}[];
const orderData = reactive<orderData>([]);
// xSheet处理数据事件 -- 生成orderData
const processDataEvent = () => {
    // 清空数据
    orderData.length = 0;
    // 获取表格数据

    const tableData = xSheet.getWork().getBody().getSheets()[0].options.tableConfig.data;

    // 第一行数据表头，直接跳过
    for (let i = 1; i < tableData.length; i++) {
        const table = tableData[i];
        // 准备数据对象
        let obj: any = {};
        // 第一个表格是标号，直接跳过，验证其他字段是否为空
        for (let j = 1; j < table.length; j++) {
            const cell = table[j];

            // 尚未检查
            obj.check = false;

            // 物料号
            if (j == 1) {
                if (cell === undefined) {
                    obj.materialNumber = '';
                } else {
                    obj.materialNumber = cell.text;
                }
            }

            // 产品名称
            if (j == 2) {
                // 验证单元格是否为空
                if (cell === undefined) {
                    obj.productName = '';
                } else {
                    obj.productName = cell.text;
                }
            }

            // 订单数量
            if (j == 3) {
                // 验证单元格是否为空
                if (cell === undefined) {
                    obj.orderNumber = 0;
                } else {
                    obj.orderNumber = Number(cell.text);
                }
            }

            // 单位
            if (j == 4) {
                if (cell === undefined) {
                    obj.unit = '只';
                } else {
                    obj.unit = cell.text;
                }
            }

            // 单价
            if (j == 5) {
                if (cell === undefined) {
                    obj.price = 0;
                } else {
                    obj.price = Number(cell.text) || 0;
                }
            }

            // 备注
            if (j == 6) {
                if (cell === undefined) {
                    obj.remark = '';
                } else {
                    obj.remark = cell.text;
                }
            }
        }

        // 添加到数组中
        orderData.push(obj);
    }

    // 去空
    for (let index = 0; index < orderData.length; index++) {
        const order = orderData[index];
        // 如果为空，直接删除
        if (order.productName == '') {
            orderData.splice(index, 1);
            index--;
            continue;
        }

        // 添加产品物料号
        order['materialNumber'] = order.materialNumber == '' ? matchProductInfo(order.productName)?.materialNumber || '' : order.materialNumber;
        // 添加产品id
        order['productId'] = matchProductInfo(order.productName)?._id || '';
        // 添加产品尺寸
        order['productSize'] = matchProductInfo(order.productName)?.productSize || '';
        // 添加价格
        order['excludTaxPrice'] = addOrderUseOnlineTable.orderTax ? Number((order.price / 1.13).toFixed(2)) : order.price;
        order['includeTaxPrice'] = addOrderUseOnlineTable.orderTax ? order.price : Number((order.price * 1.13).toFixed(2));
        // 添加小计
        order['subtotal'] =
            addOrderUseOnlineTable.orderTax == true
                ? Number((order.includeTaxPrice * order.orderNumber).toFixed(2))
                : Number((order.excludTaxPrice * order.orderNumber).toFixed(2));
    }

    if (orderData.length == 0) {
        ElMessage.warning('未检测到数据');
    } else {
        addOrderUseOnlineTable.orderAmount = orderData.reduce((prev, curr) => prev + curr.subtotal, 0);
        importConfirmVisible.value = true;
    }
};

/* ******************************检查订单交付属性/方法****************************** */
// 显示导入确认弹窗
const importConfirmVisible = ref(false);
// 检查订单交付是否正确  -- 校验orderData
const checkOrderDelivery = (item: orderData[number]): { message: string; type: any } => {
    let message = '';
    let type = '';

    if (item.includeTaxPrice == 0 && item.excludTaxPrice == 0) {
        message = '价格不能为空，至少有一项';
        type = 'danger';
        return { message, type };
    }

    if (item.orderNumber == 0) {
        message = '订单数量不能为空';
        type = 'danger';
        return { message, type };
    }

    if (addOrderUseOnlineTable.orderNo == '') {
        message = '订单编号不能为空';
        type = 'danger';
        return { message, type };
    }

    type = 'success';
    message = '√';

    item.check = true;

    return { message, type };
};
// 提交到出库
const confirmImport = () => {
    // 送货计划时间确定
    if (addOrderUseOnlineTable.orderDeliveryDate == null) {
        addOrderUseOnlineTable.orderDeliveryDate = '暂无送货计划';
    }

    // 数据校验
    if (addOrderUseOnlineTable.orderNo == '') {
        ElMessage.warning('订单编号不能为空');
        return;
    }

    // 表单数据校验
    const check = orderData.some((item) => item.check == false);
    if (check) {
        ElMessage.warning('请检查订单数据，是否有未填写的列项');
        return;
    }

    // 数据处理
    for (let index = 0; index < orderData.length; index++) {
        const orderDetail = orderData[index];
        addOrderUseOnlineTable.orderDetail.push(orderDetail);
    }

    // 添加订单
    createOrder(addOrderUseOnlineTable).then(() => {
        ElMessage({
            message: '添加订单成功',
            type: 'success',
            grouping: true,
        });
        importConfirmVisible.value = false;
        addOrderUseOnlineTableVisible.value = false;
        instance?.proxy?.$Bus.emit('updateOrderList');
    });
};
</script>

<style scoped lang="scss">
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

.online-table-container {
    height: calc(100vh - 80px);
    width: calc(100vw - 32px);
}
</style>
